// pages/driving/driving.ts
// import { rental } from "../../service/proto_gen/rental/rental_pb"
// import { TripService } from "../../service/trip"
import { TripService } from "../../service/trip"
import { formatDuration, formatFee } from "../../utils/format"
import { routing } from "../../utils/routing"

// const updateIntervalSec = 5
const initialLat = 30
const initialLng = 120
const centPerSec = 1
function durationStr(sec: number) {
    const dur = formatDuration(sec)
    return `${dur.hh}:${dur.mm}:${dur.ss}`
}
Page({

    timer: undefined as number|undefined,
    tripID: '',

    data: {
        location: {
            latitude: initialLat,
            longitude: initialLng,
        },
        scale: 12,
        elapsed: '00:00:00',
        fee: '0.00',
        markers: [
            {
                iconPath: "/resources/car.png",
                id: 0,
                latitude: initialLat,
                longitude: initialLng,
                width: 20,
                height: 20,
            },
        ],
    },
    onLoad(opt: Record<'trip_id', string>) {
        const o: routing.DrivingOpts = opt
        this.tripID = o.trip_id
        TripService.getTrip(this.tripID).then(console.log)
        TripService.getTrips().then(console.log)
        this.setupLocationUpdator()
        this.setupTimer(o.trip_id)
    },
    onUnload() {
        wx.stopLocationUpdate()
        if (this.timer) {
            clearInterval(this.timer)
        }
    },
    setupLocationUpdator() {
        wx.startLocationUpdate({
            fail: console.error,
        })
        wx.onLocationChange(loc => {
            this.setData({
                location: {
                    latitude: loc.latitude,
                    longitude: loc.longitude,
                },
            })
        })
    },
    setupTimer(tripID: string) {
        console.log(tripID)
        let elapsedSec = 0
        let cents = 0
        setInterval(()=>{
            elapsedSec++
            cents += centPerSec
            this.setData({
                elapsed:durationStr(elapsedSec),
                fee:formatFee(cents)
            })
        },1000)
    },
})